package com.zxy.util;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class  OssHandler implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(OssHandler.class);
    // 完整的OSS前缀（用于匹配正确地址）
    private static final String OSS_FULL_PREFIX = "https://jostem.oss-cn-beijing.aliyuncs.com/";
    // 可能出现的不完整前缀（少一个斜杠）
    private static final String OSS_MISSING_SLASH_PREFIX = "https:/jostem.oss-cn-beijing.aliyuncs.com/";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        log.info("后端接收的URI：{}", requestUri);

        // 1. 检查是否是少斜杠的情况，补全为完整协议
        String processedUri = requestUri;
        if (requestUri.contains(OSS_MISSING_SLASH_PREFIX)) {
            // 将 "https:/" 替换为 "https://"，补全斜杠
            processedUri = requestUri.replace(OSS_MISSING_SLASH_PREFIX, OSS_FULL_PREFIX);
            log.info("补全斜杠后的URI：{}", processedUri);
        }

        // 2. 重新定位完整的OSS前缀
        int prefixIndex = processedUri.indexOf(OSS_FULL_PREFIX);
        if (prefixIndex == -1) {
            log.error("URI中未找到OSS地址前缀，当前URI：{}", requestUri);
            response.sendError(400, "文件预览预览地址格式错误");
            return false;
        }

        // 3. 提取完整的OSS地址（从完整前缀开始截取）
        String ossUrl = processedUri.substring(prefixIndex);
        log.info("提取的OSS地址：{}", ossUrl);

        // 4. 优化重定向逻辑，确保在新标签页打开
        try {
            // 尝试直接返回文件流，让浏览器在当前页面内嵌显示
            URL url = new URL(ossUrl);
            URLConnection connection = url.openConnection();
            // 设置超时时间，避免长时间无响应
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);

            try (InputStream in = new BufferedInputStream(connection.getInputStream())) {
                // 设置响应头，指定为PDF文件并内嵌显示
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "inline; filename=\"preview.pdf\"");
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                response.setHeader("Pragma", "no-cache");

                // 写入文件流到响应
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                response.getOutputStream().flush();
                return false;
            }
        } catch (Exception e) {
            log.warn("直接返回文件流失败，将使用重定向方式：{}", e.getMessage());
            // 若文件流方式失败，降级为新标签页重定向
            response.setHeader("Location", ossUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            return false;
        }
    }
}
